<template>
  <a-space
    align="center"
    style="width: 100%; justify-content: center; margin-bottom: 16px"
  >
  <a-form
    :model="formSearchParams"
    :style="{ marginBottom: '20px' }"
    layout="inline"
    @submit="doSearch"
  >
    <a-form-item field="appName" label="测评活动名称">
      <a-input
        v-model="formSearchParams.appName"
        placeholder="请输入测评活动名称"
        allow-clear
      />
    </a-form-item>
    <a-form-item field="appDesc" label="测评活动描述">
      <a-input
        v-model="formSearchParams.appDesc"
        placeholder="请输入测评活动描述"
        allow-clear
      />
    </a-form-item>
    <a-form-item>
      <a-space>
        <a-button type="primary" html-type="submit">搜索</a-button>
        <!-- 列设置按钮 -->
        <a-popover trigger="click" title="选择要展示的列">
          <template #content>
            <a-checkbox-group
              v-model="selectedKeys"
              :options="columnOptions"
            />
          </template>
          <a-button>列设置</a-button>
        </a-popover>
      </a-space>
    </a-form-item>
  </a-form>
  </a-space>
  <a-table
    :columns="visibleColumns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total,
    }"
    @page-change="onPageChange"
  >
    <template #appIcon="{ record }">
      <a-image width="64" :src="record.appIcon" />
    </template>
    <template #appType="{ record }">
      {{ APP_TYPE_MAP[record.appType] }}
    </template>
    <template #scoringStrategy="{ record }">
      {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
    </template>
    <template #reviewStatus="{ record }">
      {{ REVIEW_STATUS_MAP[record.reviewStatus] }}
    </template>
    <template #reviewTime="{ record }">
      {{
        record.reviewTime &&
        dayjs(record.reviewTime).format("YYYY-MM-DD HH:mm:ss")
      }}
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button
          v-if="record.reviewStatus !== REVIEW_STATUS_ENUM.PASS"
          status="success"
          @click="doReview(record, REVIEW_STATUS_ENUM.PASS, '')"
        >
          通过
        </a-button>
        <a-button
          v-if="record.reviewStatus !== REVIEW_STATUS_ENUM.REJECT"
          status="warning"
          @click="doReview(record, REVIEW_STATUS_ENUM.REJECT, '不符合上架要求')"
        >
          拒绝
        </a-button>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { ref, watchEffect, computed } from "vue";
import {
  deleteAppUsingPost1,
  doAppReviewUsingPost,
  listAppByPageUsingPost,
} from "@/api/appController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import {
  APP_SCORING_STRATEGY_MAP,
  APP_TYPE_MAP,
  REVIEW_STATUS_ENUM,
  REVIEW_STATUS_MAP,
} from "@/constant/app";
import type { CheckboxOption } from "@arco-design/web-vue";


// --- 列定义 & 可视状态 ---
interface Col { title: string; dataIndex?: string; slotName?: string; key: string; }
const allColumns: Col[] = [
  { key: "id",                title: "id",               dataIndex: "id" },
  { key: "appName",           title: "名称",             dataIndex: "appName" },
  { key: "appDesc",           title: "描述",             dataIndex: "appDesc" },
  { key: "appIcon",           title: "图标",             dataIndex: "appIcon",   slotName: "appIcon" },
  { key: "appType",           title: "测评活动类型",     dataIndex: "appType",   slotName: "appType" },
  { key: "scoringStrategy",   title: "评分策略",         dataIndex: "scoringStrategy", slotName: "scoringStrategy" },
  { key: "reviewStatus",      title: "审核状态",         dataIndex: "reviewStatus",    slotName: "reviewStatus" },
  { key: "reviewMessage",     title: "审核信息",         dataIndex: "reviewMessage" },
  { key: "reviewTime",        title: "审核时间",         dataIndex: "reviewTime", slotName: "reviewTime" },
  { key: "reviewerId",        title: "审核人 id",        dataIndex: "reviewerId" },
  { key: "userId",            title: "用户 id",          dataIndex: "userId" },
  { key: "createTime",        title: "创建时间",         dataIndex: "createTime", slotName: "createTime" },
  { key: "updateTime",        title: "更新时间",         dataIndex: "updateTime", slotName: "updateTime" },
  { key: "optional",          title: "操作",             slotName: "optional" },
];

// 默认展示必要列的 key
const defaultKeys = ["appName", "appDesc", "appIcon", "appType", "optional"] as string[];
const selectedKeys = ref<string[]>([...defaultKeys]);

// 生成下拉复选框用的 options
const columnOptions = computed<CheckboxOption[]>(() =>
  allColumns.map(c => ({ label: c.title, value: c.key }))
);

// 根据 selectedKeys 过滤出可见列
const visibleColumns = computed(() =>
  allColumns
    .filter(c => selectedKeys.value.includes(c.key))
    .map(c => {
      // table 需要 title, dataIndex, slotName
      const col: any = { title: c.title, key: c.key };
      if (c.dataIndex) col.dataIndex = c.dataIndex;
      if (c.slotName) col.slotName = c.slotName;
      return col;
    })
);

const formSearchParams = ref<API.AppQueryRequest>({});

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

const searchParams = ref<API.AppQueryRequest>({
  ...initSearchParams,
});
const dataList = ref<API.App[]>([]);
const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listAppByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

/**
 * 执行搜索
 */
const doSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};

/**
 * 当分页变化时，改变搜索条件，触发数据加载
 * @param page
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.App) => {
  if (!record.id) {
    return;
  }

  const res = await deleteAppUsingPost1({
    id: record.id,
  });
  if (res.data.code === 0) {
    loadData();
  } else {
    message.error("删除失败，" + res.data.message);
  }
};

/**
 * 审核
 * @param record
 * @param reviewStatus
 * @param reviewMessage
 */
const doReview = async (
  record: API.App,
  reviewStatus: number,
  reviewMessage?: string
) => {
  if (!record.id) {
    return;
  }

  const res = await doAppReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  });
  if (res.data.code === 0) {
    loadData();
  } else {
    message.error("审核失败，" + res.data.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 表格列配置
const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "名称",
    dataIndex: "appName",
  },
  {
    title: "描述",
    dataIndex: "appDesc",
  },
  {
    title: "图标",
    dataIndex: "appIcon",
    slotName: "appIcon",
  },
  {
    title: "测评活动类型",
    dataIndex: "appType",
    slotName: "appType",
  },
  {
    title: "评分策略",
    dataIndex: "scoringStrategy",
    slotName: "scoringStrategy",
  },
  {
    title: "审核状态",
    dataIndex: "reviewStatus",
    slotName: "reviewStatus",
  },
  {
    title: "审核信息",
    dataIndex: "reviewMessage",
  },
  {
    title: "审核时间",
    dataIndex: "reviewTime",
    slotName: "reviewTime",
  },
  {
    title: "审核人 id",
    dataIndex: "reviewerId",
  },
  {
    title: "用户 id",
    dataIndex: "userId",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    slotName: "updateTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

</script>